<?php

namespace app\index\controller\activity;

use app\admin\model\activity\ActivityType;
use app\admin\model\wanlshop\Shop;
use app\common\controller\Wanlshop;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Model;

/**
 * 项目活动
 *
 * @icon fa fa-circle-o
 */
class Project extends Wanlshop
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    /**
     * ProjectActivity模型对象
     * @var \app\admin\model\activity\ProjectActivity
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\activity\ProjectActivity;

        $ActivityType = new ActivityType;
        $projectTypeList = $ActivityType->getPSTypeList('project');
        $shop = \app\index\model\wanlshop\Shop::get($this->shop->id);
        $this->view->assign("shop", $shop);
        $this->view->assign("projectTypeList", array_column($projectTypeList,'label','id'));
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['type'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('type')->visible(['label']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {
        //设置过滤方法
        $this->request->filter(['trim']);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if($params['price'] < 0){
                    $this->error('金额必须大于等于0');
                }
                $params['shop_id'] = $this->shop->id;
                $params['create_time'] = date('Y-m-d H:i:s');

                if(is_array($params['label'])){
                    foreach ($params['label'] as $k =>$v){
                        if(trim($v) == ""){
                            unset( $params['label'][$k]);
                        }
                    }
                    $params['label'] = implode(',',$params['label']) ;
                }
                $result = false;
                Db::startTrans();
                try {
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row['shop_id'] !=$this->shop->id) {
            $this->error(__('You have no permission'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if($params['price'] < 0){
                    $this->error('金额必须大于等于0');
                }
                $result = false;
                if(is_array($params['label'])){
                    foreach ($params['label'] as $k =>$v){
                        if(trim($v) == ""){
                            unset( $params['label'][$k]);
                        }
                    }
                    $params['label'] = implode(',',$params['label']) ;
                }
                Db::startTrans();
                try {
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $arr =  explode(',',$row['label']);
        while (count($arr) < 4){
            array_push($arr,"");
        }
        $row['labelAll'] = $arr;
        $this->assignconfig("row", $row);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 上架或下架
     */
    public function status($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (!in_array($row['status'],['1','2','3'])) {
            $this->error('操作错误，请联系管理员');
        }
        $data['status'] = 1;
        if($row['status'] == 1){
            $data['status'] = 2;
        }

        if ($this->request->isPost()) {
            $result = false;
            Db::startTrans();
            try {
                $result = $row->allowField(true)->save($data);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $this->model->where('shop_id', '=', $this->shop->id);
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 详情
     */
    public function detail($ids = null)
    {
        $info = $this->model->get($ids);

        if (!$info) {
            $this->error(__('No Results were found'));
        }
        $shop = Shop::get($info['shop_id']);
        $type = ActivityType::get($info['type_id']);
        $StatusList = $this->model->getStatusList();

        $info2 = [
            'Shop.shopname'=>$shop ? $shop['shopname'] : '',
            'Type.label'=> $type ? $type['label'] : '',
            'Cover_img'=>$info['cover_img'],
            'Label'=>$info['label'],
            'Sketch'=>$info['sketch'],
            'Introduction'=>$info['introduction'],
            'Start_time'=>$info['start_time'],
            'End_time'=>$info['end_time'],
            'Price'=>$info['price'],
            'Status'=>isset($StatusList[$info['status']]) ? $StatusList[$info['status']] :"",
//            'Day_num'=>$info['day_num'],
            'Sold_num'=>$info['sold_num'],
            'Address'=>$info['address'],
            'Audit_time'=>$info['audit_time'],
            'Create_time'=>$info['create_time'],

        ];

        if($info['status'] == '4'){
            $info2['Refuse']=$info['refuse'];
        }

        $this->view->assign("row", $info2);

        return $this->view->fetch();
    }



}
